package com.sinog.front.config.log;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;

/**
 * @desc 自定义日志拦截器
 * @author lzq
 * @date -
 */
@Slf4j
public class ControllerInterceptor extends HandlerInterceptorAdapter {

    private static final Pattern COMPILE = Pattern.compile("-");
    public static final ThreadLocal<ConcurrentHashMap<String, Date>> timeout = ThreadLocal.withInitial(() -> new ConcurrentHashMap());

    /**
     * 在请求处理之前回调方法
     * @param request request
     * @param response response
     * @param handler handler
     * @return boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) {
        log.info("当前会话用户数:{}",timeout.get().size());
        if (!request.getRequestURI().equals("/front/checkUserState")){
            Date lasttime = new Date();
            timeout.get().put(request.getSession().getId(),lasttime);
        }
        String requestUuid = MDC.get("requestUuid");
        if(null == requestUuid || requestUuid.isEmpty()) {
            String uuid = UUID.randomUUID().toString();
            uuid = COMPILE.matcher(uuid).replaceAll("").toUpperCase();
            MDC.put("requestUuid",uuid);
        }
        // 只有返回true才会继续向下执行，返回false取消当前请求
        return true;
    }

    /**
     * 请求处理之后回调方法
     * @param request request
     * @param response response
     * @param handler handler
     * @param modelAndView modelAndView
     */
    @Override
    public void postHandle(HttpServletRequest request,HttpServletResponse response,Object handler,ModelAndView modelAndView) {
        /* 线程结束后需要清除,否则当前线程会一直占用这个requestId值 */
        MDC.remove("requestUUID");
        //LOGGER.info("ControllerInterceptor postHandle 请求处理之后清除 logback MDC requestUUID");
    }

    /**
     * 整个请求处理完毕回调方法
     * @param request request
     * @param response response
     * @param handler handler
     * @param ex ex
     */
    @Override
    public void afterCompletion(HttpServletRequest request,HttpServletResponse response,Object handler,Exception ex) {
        /*整个请求线程结束后需要清除,否则当前线程会一直占用这个requestId值 */
        MDC.clear();
        //LOGGER.info("ControllerInterceptor afterCompletion 整个请求处理完毕清除 logback MDC requestUUID");
    }
}